<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class Objects extends CI_Controller {

        function __construct()
        {
            parent::__construct();
            $this->load->model('partners_model');
            $this->load->model('objects_model');
        }

        public function index(){$this->view_all();}

        public function view_new()
        {
            $this->data = array(
                'title' => "New object",
                'post_action' => "NEW",
                'owners' => $this->partners_model->view_all_partners()
            );
            $this->template->build('objects/edit_object',$this->data); 
        }
        
        public function view_new_description($object_TYPE)
        {
            $this->load->model('groups_to_object_model','gtb_model');
            $this->load->helper('inflector');
            $this->data = array(
                'title' => "Description",
                'post_action' => "NEW",
                'type' => $object_TYPE,
                'groups' => $this->gtb_model->get_object_groups($object_TYPE)
            );
            $this->firephp->log($this->data);
            $this->template->build('objects/description',$this->data); 
        }
        
        

        function view_edit($object_ID){

            $this->data = array(
                'title' => "Edit object",
                'post_action' => "EDIT",
                'owners' => $this->partners_model->view_all_partners(),
                'object' => $this->objects_model->view_edit($object_ID)
            );
            $this->template->build('objects/edit_object',$this->data);            
        }

        public function view_all()
        {
            $this->data = array(
                'title' => "Hotels",
                'objects' => $this->objects_model->view_all()
            );
            $this->template->build('objects/view_all_objects',$this->data);
        }

        public function build_form($group_ID=1)
        {
            // Todo: Order attributes with DB queries to mech order column, null order values should be last
            $this->load->helper('inflector');
            $html = $this->objects_model->build_form($this->input->post('type'),$group_ID);
            echo json_encode(array('html'=>$html));  
        }

        public function submit_post()
        {
            /*General*/
            if($_POST['editObjectDialog_post_action']=='NEW'):
                $this->form_validation->set_rules('editObjectDialog_object_type', 'type', 'callback_dropdown_check'); 
                endif;
            $this->form_validation->set_rules('editObjectDialog_owner', 'supplier', 'callback_dropdown_check'); 
            $this->form_validation->set_rules('name', 'name', 'required');

            /*Validate custom required fields*/
            $object_attributes = $this->objects_model->validate_custom($_POST['editObjectDialog_object_type']);

            /*Trace code*/
            //$this->firephp->log($this->db->last_query());
            //$this->firephp->log($object_attributes);

            $this->load->helper('inflector');

            foreach ($object_attributes as $object_attribute):
                $name_id = preg_replace('/[^a-zA-Z0-9_%\[().\]\\/-]/s', '', camelize($object_attribute['name']));
                $this->form_validation->set_rules($name_id, $object_attribute['name'], 'required');
                endforeach;

            $this->form_validation->set_message('required','Please enter object <b>%s</b>!');

            if ($this->form_validation->run('object_attributes') == FALSE)
            {
                echo json_encode(array('action'=>FALSE, 'msg'=>validation_errors()));
            } 
            else
            {                            

                //Start entering Object
                //For custom fields we use serialize
                //a:8:{s:13:"numberOfStars";s:7:"5 stars";s:18:"distanceFromTheSea";s:5:"400 m";s:21:"distanceFromTheCenter";s:4:"1 km";s:12:"contactPhone";s:0:"";s:10:"contactFax";s:0:"";s:7:"address";s:0:"";s:14:"searchPriority";s:0:"";s:9:"infantAge";s:0:"";}



                $post_action = $_POST['editObjectDialog_post_action'];
                $record['type'] = $_POST['editObjectDialog_object_type'];
                $destination = $_POST['editObjectDialog_destination']; 
                $record['owners_ID'] = $_POST['editObjectDialog_owner'];;
                $record['name'] = $_POST['name'];
                $record['status'] = 1;
                $record['date_time'] = time();                

                unset($_POST['editObjectDialog_post_action']);
                unset($_POST['editObjectDialog_object_type']);
                unset($_POST['editObjectDialog_destination']);
                unset($_POST['editObjectDialog_owner']);
                unset($_POST['name']);

                //$this->firephp->info($_POST);
                //exit;

                switch ($post_action) {
                    case 'NEW':
                        $record['fields'] = serialize($_POST);
                        $this->firephp->info($record);
                        $this->db->insert('objects',$record);

                        if ($this->db->affected_rows() == '1')
                        {
                            echo json_encode(array('action'=>true,'msg'=>'Successful insert operation.'));
                        }else
                        {
                            echo json_encode(array('action'=>FALSE, 'msg'=>'<p>An Error Occured.</p>')); 
                        }
                        break;
                    case 'EDIT':
                        $object_ID = $_POST['editObjectDialog_post_ID'];
                        unset($_POST['editObjectDialog_post_ID']);

                        $record['fields'] = serialize($_POST);
                        //$this->firephp->info($record);
                        $this->db->where('ID',$object_ID);
                        $this->db->update('objects',$record);

                        if ($this->db->affected_rows() >= '0')
                        {
                            echo json_encode(array('action'=>true,'msg'=>'Successful edit operation.'));
                        }else
                        {
                            echo json_encode(array('action'=>FALSE, 'msg'=>'<p>An Error Occured.</p>')); 
                        }
                        break;
                }

            }

        }

        function delete($post_ID){

            if($this->objects_model->delete($post_ID)){
                $this->view_all();
            }else{
                echo 'Error ocured';
                //$this->view_all();
            }

        }

        function dropdown_check($str)
        {
            if ($str == '0')
            {
                $this->form_validation->set_message('dropdown_check', 'Please choose object <b>%s</b>!');
                return FALSE;
            }
            else
            {
                return TRUE;
            }
        }
}